//产品线 0 蜜哆哆 1 蜜雅阁 2 品牌馆
var cateType=0;

var curCatePath="未选择分类";

$(function() {
    create_tree(cateType);//生成树
    var instance = $('#jstree_demo').jstree(true);
});

function lv1_create() {
    var instance = $('#jstree_demo').jstree(true);
    instance.deselect_all();
    sel = instance.get_selected();
    if (!sel.length) {
        cateType=$("#cateType").val();
        node_create(instance,true,cateType);
    }
};

$("#cateType").change(function(){
    cateType=$("#cateType").val();
    console.log(cateType);
    $.jstree.destroy('#jstree_demo');
//        $('#jstree_demo').empty();
    create_tree(cateType);
});

//新建node
function node_create(instance,if_root,cateType){
    var parent;
//        是否是新建根节点
    if(if_root){
        instance.deselect_all();
        parent="#";
    }else{
        //当前是否有选中的节点
        if(instance.get_selected().length=0)
            return;
        parent=instance.get_selected()[0];
    }
    instance.create_node(parent, {
        "text": "",
        "type": "root"
    }, "last", function (node) {
        instance.deselect_all();
        instance.select_node(node.id);
        //启用编辑，编辑后才保存新建的node
        instance.edit(node.id,"" , function (data) {
            if(data.text==""){
                alert("名称不能为空");
                instance.delete_node(node.id);
                return;
            }
            var postdata = "{";
            postdata += '"title":"' + data.text + '"';
            postdata += ',"cateType":"' + cateType + '"';
            // postdata+=',"classifyType":"'+data.parent+'"';
            if(!if_root)
                postdata += ',"classifyType":"' + parent + '"';
            postdata += "}";
            console.log(data);
            $.ajax({
                type: "post",
                url: urlcore + "/api/classify/addClassify",
                contentType: "application/json;charset=utf-8",
                data: postdata,
                success: function (cbdata) {
                    var id = parseInt(cbdata.data.id);
                    // $(data.rslt.obj).attr("id", "li_" + data1.d);
                    instance.set_id(node, id);
                    instance.deselect_all();
                    instance.select_node(id);
                    console.log("- -insert and update success,data:" + cbdata);
                },
                error: function () {
                    alert("添加失败，请刷新后重试");
                }
            });
        });
    });

}

function create_tree(cateType){
    $.ajax({
        url:urlcore+"/api/classify/getTree",
        type:"get",
        contentType:"application/x-www-form-urlencoded; charset=utf-8",
        dataType:"json",
        data:{cateType:cateType},
        success:function(treedata){
            console.log(treedata);
            $('#jstree_demo').on("select_node.jstree", function(e, data) {
                var instance = $('#jstree_demo').jstree(true);
                console.log("selected的data数据", data.selected);
            }).on("changed.jstree", function(e, data) {
                curCatePath="";
                //当有节点被选中时
                if (data.selected.length) {
                    curCatePath = data.instance.get_path(data.selected[0], ">", 0);
                    //获取当前选择目录路径
                    console.log("selected的data数据", data.instance.get_path(data.selected[0], ">", 0));
                    $("#curCatePath").text(curCatePath);
                    var slcnode = {
                        id: data.node.id,
                        parent: data.node.parent,
                        text: data.node.text
                    };
                    console.log(slcnode);
                    console.log('The selected node\'s is: ' + data.instance.get_node(data.selected[0]).text);
                    console.log("selected node original data is :",data.node.original);
                    /**
                     *业务start
                     */
                    //刷新fileinput插件
                    $("#fileupload2").fileinput("refresh");
                    //清空记录的旧图信息
                    $("#oldpic").html("");
                    var original = data.node.original;
                    var picSrc = original.picture_url;
                    if (picSrc == undefined) {
                        $('#previous_picture_div').hide();
                    }else{
                        $('#previous_picture_div').css("display", "block");
                        var imgStr1 = "";
                        imgStr1 +=
                            '<div style="position:relative;width:180px;height:auto;float:left;" display="block">' +
                            '	<img style="padding: 5px 5px 5px 5px;" width="auto" height="150px" src="' + picSrc + '">' +
                            '</div>';
                        $('#pictureUrl').html(imgStr1);
                    }

                    /**
                     *业务end
                     */
                }
            })
                .jstree({
                    'core': {
                        'multiple': false,
                        'check_callback': function(operation, node, parent, position, more) {
                            if (operation === 'create_node') {
                                console.log('create测试');
                                console.log('create测试的parent.id=', parent.id, ',create测试的parent.text=', parent.text);
                                // node.id="zzzz";
                            }
                            if (operation === 'delete_node') {
                                console.log('delete测试');
                                console.log("delete节点的id=", node.id, ",delete节点的text=", node.text)
                                console.log(node.text);
                                console.log(position);

                            }
                            if (operation === 'rename_node') {
                                console.log('rename测试');
                                console.log("rename节点的id=", node.id)
                                console.log("parent.id:", parent.id, ",parent.text:", parent.text);
                                console.log("原来text:", node.text, ",rename后的text:", position);

                            }
                            console.log('测试区域');
                            return true;
                        },
                        'data':    treedata
                        /*		[{
                                "id": "ajson1",
                                "parent": "#",
                                "text": "Simple root node",
                                "pictureUrl":"zz"
                            }, {
                                "id": "ajson2",
                                "parent": "#",
                                "text": "Root node 2",
                                "pictureUrl":"yy"
                            }, {
                                "id": "ajson3",
                                "parent": "ajson2",
                                "text": "Child 1",
                                "pictureUrl":"zrrz"
                            }, {
                                "id": "ajson4",
                                "parent": "ajson2",
                                "text": "Child 2",
                                "pictureUrl":"z1z"
                            }, ]*/

                    },
                    'plugins': [ //插件，下面是插件的功能
                        'types', //可以设置其图标，在上面的一样。
                        'contextmenu', //文本菜单
                        'wholerow', //
//                    'sort', //排序，添加node后会自动排序，影响回调中的编辑操作
                        // 'unique', //独特----防止重复。(新添加的)
//                    'dnd', //提供拖放功能
                        'search' //启用搜索
                    ],
                    'types': {
                        "#": {
                            "max_depth": 3,
                            "valid_children": ["root"]
                        }
                    },
                    'contextmenu': {
                        "items": {
                            "create": {
                                "label": "新增",
                                "action": function() {
                                    var instance = $('#jstree_demo').jstree(true);
                                    var cur = instance.get_selected();
                                    //当前节点为父节点新建node
                                    node_create(instance,false,cateType);
                                }
                            },
                            "rename": {
                                "label": "修改",
                                "action": function() {
                                    var instance = $('#jstree_demo').jstree(true);
                                    var cur = instance.get_selected();
                                    var oldtext=instance.get_node(cur).text;
                                    instance.edit(cur, null, function(data) {
                                        if(data.text==oldtext)
                                            return;
                                        if(data.text==""){
                                            alert("名称不能为空!");
                                            return;
                                        }
                                        console.log(data);
                                        var postdata="{";
                                        postdata+='"id":'+data.id+',"title":"'+data.text+'"';
                                        // postdata+=',"classifyType":"'+data.parent+'"';
                                        postdata+="}";
                                        $.ajax({
                                            type: "post",
                                            url: urlcore+"/api/classify/update",
                                            contentType: "application/json;charset=utf-8",
                                            data: postdata,
                                            success: function(cbdata) {
                                                console.log("--update success,data:"+cbdata);
                                            },
                                            error: function() {
                                                alert("修改失败，请刷新后重试!");
                                            }
                                        });
                                    });
                                }
                            },
                            "delete": {
                                "label": "删除",
                                "action": function() {
                                    var instance = $('#jstree_demo').jstree(true);
                                    var cur = instance.get_node(instance.get_selected());
                                    postdata='{"id":"'+cur.id+'"';
                                    if (cur.children.length > 0) {
                                        if (!confirm("要删除的分类中还有数据，确定删除吗")) {
                                            return;
                                        }
                                        postdata+=',"rec":"1"';//级联删除其下的子节点
                                    }
                                    postdata += "}";
                                    $.ajax({
                                        type: "post",
                                        url: urlcore + "/api/classify/delete",
                                        contentType: "application/json;charset=utf-8",
                                        data: postdata,
                                        success: function(cbdata) {
                                            console.log("--delete success,data:" + cbdata);
                                            console.log("---delete node", cur);
                                            instance.delete_node(cur);
                                        },
                                        error: function() {
                                            alert("删除失败，该分类下还有商品存在，请稍后再试");
                                        }
                                    });

                                }
                            }
                        }
                    }
                });
        },
        error:function() {
            alert("获取分类树失败，请刷新后重试");
        }
    });

}

//输入框输入定时自动搜索
var to = false;
$('#search_ay').keyup(function(){
    if (to) {
        clearTimeout(to);
    }
    to = setTimeout(function() {
        node_search();
    }, 250);
});
$('#btn_search').on('click',function() {
    node_search();
});

function node_search(){
    var instance = $('#jstree_demo').jstree(true);
    instance.deselect_all();
    instance.search($('#search_ay').val());
}

$('#btn_refresh_tree').on('click',function(){
/*    var ins = $('#jstree_demo').jstree(true);
    ins.refresh();*/
    cateType=$("#cateType").val();
    console.log(cateType);
    $.jstree.destroy('#jstree_demo');
    curCatePath="未选择分类";
    $("#curCatePath").text(curCatePath);//goods_add.js中的
//        $('#jstree_demo').empty();
    create_tree(cateType);
});

/*
function getTreePath(){

}
$('#jstree_demo').on("select_node.jstree", function(e, data) {
    var instance = $('#jstree_demo').jstree(true);
    curCatePath=data.instance.get_path(data.selected[0],">",0);
    //获取当前选择目录路径
    console.log("selected的data数据", data.instance.get_path(data.selected[0],">",0));
    // $("#curCatePath").text(curCatePath);
});*/
